<template>
  <div id="userManagePage">
    <div class="page-header">
      <h2>用户管理</h2>
      <a-button type="primary" @click="showAddModal">
        <PlusOutlined />
        添加用户
      </a-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <a-input-search
        v-model:value="searchKeyword"
        placeholder="请输入用户名搜索"
        style="width: 300px"
        @search="handleSearch"
        @change="handleSearchChange"
      />
    </div>

    <!-- 用户列表表格 -->
    <a-table
      :columns="columns"
      :data-source="userStore.userList"
      :loading="userStore.loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这个用户吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
        <template v-else-if="column.key === 'createTime'">
          {{ formatDate(record.createTime) }}
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑用户弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      ok-text="确定"
      cancel-text="取消"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="formState.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="用户账号" name="userAccount">
          <a-input v-model:value="formState.userAccount" placeholder="请输入用户账号" />
        </a-form-item>
        <a-form-item v-if="!isEdit" label="密码" name="userPassword">
          <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="用户角色" name="userRole">
          <a-select v-model:value="formState.userRole" placeholder="请选择用户角色">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="用户简介" name="userProfile">
          <a-textarea v-model:value="formState.userProfile" placeholder="请输入用户简介" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance, TableColumnsType } from 'ant-design-vue'
import { useUserManageStore } from '@/stores/userManageStore'
import type { User, UserForm } from '@/types/user'

// 使用用户管理 store
const userStore = useUserManageStore()

// 表单相关
const formRef = ref<FormInstance>()
const modalVisible = ref(false)
const isEdit = ref(false)
const currentUserId = ref<number>()

// 搜索相关
const searchKeyword = ref('')

// 表单数据
const formState = reactive<UserForm>({
  userName: '',
  userAccount: '',
  userPassword: '',
  userProfile: '',
  userRole: 'user'
})

// 表格列配置
const columns: TableColumnsType = [
  {
    title: '用户ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName'
  },
  {
    title: '用户账号',
    dataIndex: 'userAccount',
    key: 'userAccount'
  },
  {
    title: '用户简介',
    dataIndex: 'userProfile',
    key: 'userProfile',
    ellipsis: true
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    key: 'userRole',
    customRender: ({ text }) => text === 'admin' ? '管理员' : '普通用户'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
]
//分页配置
const pagination = computed(() => ({
  current: userStore.currentPage,
  pageSize: userStore.pageSize,
  total: userStore.total,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
}))

/**
 * 加载用户列表
 */
const loadUserList = () => {
  userStore.fetchUserList({
    current: userStore.currentPage,
    pageSize: userStore.pageSize,
    userName: searchKeyword.value
  })
}

/**
 * 显示编辑用户弹窗
 */
const showEditModal = (record: User) => {
  isEdit.value = true
  currentUserId.value = record.id
  modalVisible.value = true
  
  // 填充表单数据
  formState.userName = record.userName
  formState.userAccount = record.userAccount
  formState.userProfile = record.userProfile || ''
  formState.userRole = record.userRole
  formState.userPassword = '' // 编辑时不显示密码
}

/**
 * 重置表单
 */
const resetForm = () => {
  formState.userName = ''
  formState.userAccount = ''
  formState.userPassword = ''
  formState.userProfile = ''
  formState.userRole = 'user'
  formRef.value?.resetFields()
}

/**
 * 处理表单提交
 */
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    if (isEdit.value && currentUserId.value) {
      // 编辑用户
      await userStore.updateUser(currentUserId.value, formState)
      message.success('用户更新成功')
    } else {
      // 添加用户
      await userStore.addUser(formState)
      message.success('用户添加成功')
    }
    
    modalVisible.value = false
    loadUserList()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 取消弹窗
 */
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

/**
 * 删除用户
 */
const handleDelete = async (userId: number) => {
  try {
    await userStore.deleteUser(userId)
    message.success('用户删除成功')
    loadUserList()
  } catch (error) {
    message.error('删除失败')
  }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
  userStore.currentPage = 1
  loadUserList()
}

/**
 * 处理搜索输入变化
 */
const handleSearchChange = () => {
  if (!searchKeyword.value) {
    handleSearch()
  }
}

/**
 * 处理表格变化（分页、排序等）
 */
const handleTableChange = (pag: any) => {
  userStore.currentPage = pag.current
  userStore.pageSize = pag.pageSize
  loadUserList()
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}
</script>

<style scoped>
#userManagePage {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.search-area {
  margin-bottom: 16px;
}
</style>
